package com.xxx.topapplication;

import android.app.ActivityManager;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import java.lang.ref.WeakReference;
import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author hdz
 * @date 2019/08/07
 */
public class TopActivityListener {

    private static final String TAG = "TopActivityListener";

    private UsageStatsManager mUsageStatsManager;
    private ActivityManager mActivityManager;
    private WeakReference<Context> mWeakContext;
    private Callback mCallback = null;
    private String mPkgName = "";

    /**
     * 基于相对时间，不受系统时间的改变所影响
     */
    private ScheduledExecutorService mTimer;

    public TopActivityListener(Context context, Callback callback) {
        init(context);
        mWeakContext = new WeakReference<>(context);
        this.mCallback = callback;

        mTimer = new ScheduledThreadPoolExecutor(1);

        //该方法设置了执行周期，下一次执行时间相当于是上一次的执行时间加上period，它是采用已固定的频率来执行任务
        mTimer.scheduleAtFixedRate(new TestTimeTask(), 0, 1, TimeUnit.SECONDS);
    }

    private void init(Context context) {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            // 获取应用使用数据统计管理器
            mUsageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
        } else {
            //获取到进程管理器
            mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        }
    }



    class TestTimeTask extends TimerTask {
        @Override
        public void run() {
            AppInfo appInfo;
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
                appInfo = getTopAppInfo6();
            } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) {
                appInfo = getTopAppInfo5();
            } else {
                appInfo = getTopAppInfo4();
            }
            if (appInfo != null) {
                if (!appInfo.getPackageName().equals(mPkgName)) {
                    mPkgName = appInfo.getPackageName();
                    if (mCallback != null) {
                        mCallback.onCurrentApplicationChanged(appInfo);
                    }
                }
            }
        }
    }

    public void release() {
        stopTimer();
    }

    private void stopTimer() {
        if (mTimer != null) {
            mTimer.shutdown();
            mTimer = null;
        }
    }

    public interface Callback {
        void onCurrentApplicationChanged(AppInfo appInfo);
    }



    private AppInfo getTopAppInfo4() {
        //获取到当前正在运行的任务栈，参数是想获得的个数，可以随意写
        List<ActivityManager.RunningTaskInfo> tasks = mActivityManager.getRunningTasks(1);

        //获取到最上面的进程
        ActivityManager.RunningTaskInfo taskInfo = tasks.get(0);

        //获取到最顶端应用程序的包名和Activity名
        String topPackageName = taskInfo.topActivity.getPackageName();

        //获取到最顶端应用程序的Activity名
        String topActivityName = taskInfo.topActivity.getClassName();

        Log.d(TAG, "top running app is : "+topPackageName);
        Log.d(TAG, "top running app is : "+topActivityName);
        return getAppInfo(mWeakContext.get(), topPackageName);
    }


    private AppInfo getTopAppInfo5() {
        // 获取正在运行的应用进程
        List<ActivityManager.RunningAppProcessInfo> tasks = mActivityManager.getRunningAppProcesses();

        if (null != tasks && tasks.size() > 0) {
            // 获取顶端应用，只能获取到应用包名
            String pkgName = tasks.get(0).processName;
            return getAppInfo(mWeakContext.get(), pkgName);
        }
        return null;
    }


    private AppInfo getTopAppInfo6() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (mUsageStatsManager != null) {
                // 获取最近30秒之内的应用数据
                long endTime = System.currentTimeMillis();
                long beginTime = endTime - 30 * 1000;
                String topPackageName = "";
                // 按指定时间获取应用使用数据统计
                List<UsageStats> stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, beginTime, endTime);
//                Log.i(TAG, "Running app number in last 30 seconds : " + stats.size());

                //取得最近运行的一个app，即当前运行的app
                if (!stats.isEmpty()) {
                    int top = 0;
                    for (int index = 0; index < stats.size(); index++) {
                        // 获取最近时刻的应用所在索引
                        if (stats.get(index).getLastTimeUsed() > stats.get(top).getLastTimeUsed()) {
                            top = index;
                        }
                    }
                    // 获取应用包名
                    topPackageName = stats.get(top).getPackageName();
                }
//                Log.d(TAG, "top running app is : "+topPackageName);
                return getAppInfo(mWeakContext.get(), topPackageName);
            }
        }
        return null;
    }



    /**
     * 获取其它应用信息
     * @param context Context
     * @param packageName 应用包名
     */
    public AppInfo getAppInfo(Context context, String packageName) {
        if (TextUtils.isEmpty(packageName)) {
            return null;
        }
        //Log.d("==", "getAppInfo: " + packageName);
        // 获取包管理器
        PackageManager pm = context.getPackageManager();
        try {
            // 根据包名获取ApplicationInfo
            ApplicationInfo appInfo = pm.getApplicationInfo(packageName, 0);
            // 获取应用图标
            Drawable icon = appInfo.loadIcon(pm);
            Drawable appIcon = pm.getApplicationIcon(packageName);
            // 获取应用名称
            String label = appInfo.loadLabel(pm).toString();

            // 根据包名获取PackageInfo
            PackageInfo pkgInfo = pm.getPackageInfo(packageName, 0);
            // 获取应用版本号
            String versionName = pkgInfo.versionName;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                versionName += "(" + pkgInfo.getLongVersionCode() + ")";
            } else {
                versionName += "(" + pkgInfo.versionCode + ")";
            }

            // 安装路径
            String apkPath = appInfo.sourceDir;

            return new AppInfo(packageName, label, versionName, icon, apkPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
